package mysql

import (
	"bluebell_qimi/models"
	"errors"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

// 查询所有社区列表
//1. sqlx版
/*func GetCommunityList() (communityList []models.Community, err error) {
	//查数据库
	sqlStr := "select community_id,community_name from community"
	if err := db.Select(&communityList, sqlStr); err != nil {
		if err == sql.ErrNoRows {
			zap.L().Warn("there is no community in db")
			err = nil
		}
	}
	return
}*/

// 2. gorm版
func GetCommunityList() ([]models.Community, error) {
	var communityList []models.Community
	//查数据库
	if err := db.Debug().Table("communitydetails").Select("ID", "CommunityName").Find(&communityList).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			zap.L().Warn("there is no community in db")
			err = nil
		} else {
			return communityList, err
		}
	}
	return communityList, nil
}

// 根据communityid获取社区详情
//1. sqlx版
/*func GetCommunityDetailByID(id int64) (community *models.CommunityDetail, err error) {
	community = new(models.CommunityDetail)
	sqlStr := `select community_id,community_name,introduction,create_time
			from community
			where community_id=?`
	if err = db.Get(community, sqlStr, id); err != nil {
		if err == sql.ErrNoRows {
			err = ErrorInvalidID
		}
	}
	return
}*/

// 2. gorm版
func GetCommunityDetailByID(id int64) (communityDetail *models.CommunityDetail, err error) {
	communityDetail = new(models.CommunityDetail)
	err = db.Table("communityDetails").Where("community_id=?", id).First(&communityDetail).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		zap.L().Warn("there is no GetCommunityDetail in db")
		return nil, err
	}
	return
}
